<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\model\Sms;

class PayController extends BaseController
{
    /**
     * 个人钱包信息接口
     * by 吉星
     */
    // 个人钱包获取余额等数据
    public function statement(Request $request){
        if($request){
            $uid = $request->get('id');
            // echo "<pre>";
            // dump($uid);die();
            $user = Db:: table('social_user')->where('id',$uid)->first();  //查询用户信息
            $user =  json_decode(json_encode($user),true);
            // 获取订单中占用的金额
            $result = Db::table('order')
                // ->select("SUM(order.price) as count","SUM(order.cip_number) as cipnum")
                ->select("order.price as count")
                ->join('social_user','social_user.id','=','order.user_id')
                ->where('social_user.id','=',$uid)
                ->whereBetween('order.status',array(1,8))
                // ->where('a.pay_from','=',1)
                ->where('order.jsjcs','=',1)
                ->first();
            $result =  json_decode(json_encode($result),true);

            // 获取充值记录列表
            $uid = $user['id'];
            $paylist = Db::table('social_recharge_log')
                ->where('source_id',$uid)
                ->where('source',0)
                ->where('status',0)
                ->get()
                ->toArray();
            $paylist =  json_decode(json_encode($paylist),true);
            // 用户余额 $user['sum_money'] 企业剩余限额 $user['left_price']  进行中订单占用余额 $result['count'] 充值记录 $paylist
            return ['user'=>$user,'order'=>$result,'code'=>1000,'paylist'=>$paylist,'message'=>'获取数据成功！'];
        }else{
            return ['code'=>1001,'message'=>'获取数据失败，未查询到用户信息！'];
        }
    }

    // 出行卡页面赋值
    public function card(Request $request){

        if($request){
            $uid = $request->get('id');
            // 获取用户信息 user
            $user = Db::table('social_user')->where('id',$uid)->first();
            $user =  json_decode(json_encode($user),true);

            // 获取绑定的出行卡 card  count1为出行卡剩余总金额，count2为绑定的每一种出行卡数量
            $card = Db::table('wakeup_card')
                ->select('*',DB::raw("sum(lost_price) as count1,COUNT(type) as count2"))
                ->where('uid',$uid)
                ->where('lost_price','>',0)
                ->where('from','=',2)
                ->groupBy('type')
                ->get()
                ->toArray();
            $card =  json_decode(json_encode($card),true);

            // 可购买的出行卡列表 cardlist
            $cardlist = Db::table('card')
                ->where('status','=',1)
                ->get()
                ->toArray();
            $cardlist =  json_decode(json_encode($cardlist),true);

            // 绑定的出行卡列表 wake_cardlist
            $wake_cardlist = Db::table('wakeup_card')
                ->where('uid','=',$uid)
                ->where('from','=',2)
                ->get()
                ->toArray();
            // ->paginate(10);
            $wake_cardlist =  json_decode(json_encode($wake_cardlist),true);

            // 购买的出行卡列表
            $buy_cardlist = Db::table('buy_card')
                ->where('uid','=',$uid)
                ->where('company_id','=',null)
                ->get()
                ->toArray();
            // ->paginate(10);
            $buy_cardlist =  json_decode(json_encode($buy_cardlist),true);
            return ['user'=>$user,'card'=>$card,'code'=>1000,'cardlist'=>$cardlist,'wake_cardlist'=>$wake_cardlist,'buy_cardlist'=>$buy_cardlist,'message'=>'获取数据成功！'];
        }else{
            return ['code'=>1001,'message'=>'获取数据失败，未查询到用户信息！'];
        }
    }

    // 个人购买出行卡
    public function buycard(Request $request){
        if($request){
            $uid = $request->get('id');
            // 获取用户信息
            $user = Db::table('social_user')
                ->where('id',$uid)
                ->first();
            $user =  json_decode(json_encode($user),true);
            // 接收要购买的出行卡ID
            $cid = '';
            if(!empty($request['card_id'])){
                $cid = $request['card_id'];
            }
            // 接收购买的出行卡总金额以及购买数量
            $money = $request['money']?$request['money']:'';
            $cardnum = $request['cardnum']?$request['cardnum']:'';
            // 获取购买的出行卡信息
            $cardinfo = Db::table('card')
                ->where('id',$cid)
                ->first();
            $cardinfo =  json_decode(json_encode($cardinfo),true);
            if($cardinfo && $user){
                if($user['sum_money'] - $money < 0){
                    return  ['code'=>1003,'message'=>'购买失败：账户余额不足，请充值后再购买！'];
                }else{
                    // 购买成功，更新账户信息
                    $left_price = $user['sum_money'] - $money;
                    $upuser = ['sum_money'=>$left_price,'update_at'=>time()];  // 更新余额信息,扣除对应的购买金额
                    $usersave = Db::table('social_user')->where('id',$user['id'])->update($upuser);
                    for ($i=0; $i < $cardnum; $i++) {
                        $data = [
                            'name'=>$cardinfo['name'],
                            'type'=>$cardinfo['type'],
                            'status'=>0,
                            'price'=>$cardinfo['price'],
                            'pic'=>$cardinfo['pic'],
                            'card_number'=>date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                            'card_password'=>time().str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                            'cid'=>$cid,
                            'uid'=>$uid,
                            'create_time'=>time()
                        ];
                        $buycard[$i] = Db::table('buy_card')->insertGetId($data);

                    }
                    $buycardid = implode(',', $buycard);
                    $buycardlist = Db::table('buy_card')
                        ->whereIn('id',$buycard)
                        ->get()
                        ->toArray();
                    $buycardlist =  json_decode(json_encode($buycardlist),true);
                    // 给用户发送卡号密码短信
                    $mes = new Sms();
                    $mobile = $user['phone'];
                    for ($s=0; $s < $cardnum; $s++) {
                        $msg = "【时代出行】恭喜您购买了一张".$buycardlist[$s]['name']."，面额".$buycardlist[$s]['price']."元，卡号".$buycardlist[$s]['card_number']."，密码".$buycardlist[$s]['card_password']."，请在应用商店搜索下载时代出行APP绑定使用【时代出行】";
                        $res = $mes->sendSMS($mobile,$msg);
                    }
                    // dump($buycardlist);
                    return  ['code'=>1000,'message'=>'购卡成功！','buycardlist'=>$buycardlist];
                }
            }else{
                return  ['code'=>1002,'message'=>'获取数据失败：未找到要购买的出行卡信息！'];
            }
        }else{
            return ['code'=>1001,'message'=>'获取数据失败，未查询到用户信息！'];
        }
    }

    // 赠送出行卡
    public function sendcard(request $request){
        if($request){
            $buy_userid = '';
            $phone = '';
            $card_id = '';
            // 获取赠送人ID
            if(!empty($request['buy_userid'])){
                $buy_userid = $request['buy_userid'];
            }
            // 获取赠送人信息
            $buy_userinfo = Db::table('social_user')
                ->where('id',$buy_userid)
                ->first();
            $buy_userinfo =  json_decode(json_encode($buy_userinfo),true);
            // 获取受赠人手机号
            if(!empty($request['phone'])){
                $phone = $request['phone'];
            }
            // 获取用户信息
            $user = Db::table('social_user')
                ->where('phone',$phone)
                ->first();
            $user =  json_decode(json_encode($user),true);
            // 获取赠送卡ID
            if(!empty($request['card_id'])){
                $card_id = $request['card_id'];
            }

            // $card_id = implode(',', $card_id);
            if($user){
                $cardlist = Db::table('buy_card')
                    ->whereIn('id',$card_id)
                    ->where('status',0)
                    ->get()
                    ->toArray();
                $cardlist =  json_decode(json_encode($cardlist),true);
                $mes = new Sms();
                $mobile = $phone;
                for ($i=0; $i < count($cardlist); $i++) {
                    $savedate['update_time']=time();
                    $savedate['status']=2;
                    $insertdate['uid'] = $buy_userid;
                    $insertdate['get_userid'] = $user['id'];
                    $insertdate['buy_card_id'] = $cardlist[$i]['id'];
                    $insertdate['create_time'] = time();
                    $saveid = $cardlist[$i]['id'];
                    $add = Db::table('send_card')->insert($insertdate);
                    $update = Db::table('buy_card')->where('id','=',$saveid)->update($savedate);
                    $msg = "【时代出行】用户尾号".substr($buy_userinfo['phone'], 7,4)."为您赠送一张".$cardlist[$i]['name']."，面额".$cardlist[$i]['price']."元，卡号".$cardlist[$i]['card_number']."，密码".$cardlist[$i]['card_password']."，请在应用商店搜索下载时代出行APP绑定使用【时代出行】";
                    // 发送短信,获得回执
                    $res = $mes->sendSMS($mobile,$msg);
                }
                return ['code'=>1000,'message'=>'赠送成功，短信已发送到受赠人手机号，请提醒对方查收！'];
            }else{
                return ['code'=>1001,'message'=>'很抱歉，受赠人手机号不存在，你可以先联系对方下载时代出行APP并且注册后即可赠送！'];
            }
        }
    }

    // 绑定出行卡
    public function wakecard(Request $request){
        if($request){
            // 获取绑定的出行卡ID 及信息
            $card_id = $request['card_id'] ? $request['card_id'] : '';
            // 获取绑定的用户信息
            if(!empty($request->get('id'))){
                $uid = $request->get('id');
            }
            $user = Db::table('social_user')
                ->where('id',$uid)
                ->first();
            $user = json_decode(json_encode($user),true);
            if($user){
                if($card_id){
                    $card_list = Db::table('buy_card')
                        ->whereIn('id',$card_id)
                        ->where('uid',$uid)
                        ->where('status','<>',1)
                        ->get()
                        ->toArray();
                    $card_list = json_decode(json_encode($card_list),true);
                    if($card_list){
                        for ($i=0; $i < count($card_list); $i++) {
                            //绑定
                            $upbuycard = ['update_time'=>time(),'status'=>1];
                            $data = [
                                'uid'=>$uid,
                                'buy_card_id'=>$card_list[$i]['id'],
                                'card_name'=>$card_list[$i]['name'],
                                'card_num'=>$card_list[$i]['card_number'],
                                'card_price'=>$card_list[$i]['price'],
                                'type'=>$card_list[$i]['type'],
                                'lost_price'=>$card_list[$i]['price'],
                                'create_time'=>time(),
                                'from'=>2
                            ];
                            $bangding = Db::table('buy_card')->where('id',$card_list[$i]['id'])->update($upbuycard);
                            $jihuo = Db::table('wakeup_card')->insert($data);
                        }
                        return ['code'=>1000,'message'=>'恭喜您,绑卡成功!'];
                    }else{
                        return ['code'=>1001,'message'=>'很抱歉,出行卡不符合绑定条件!'];
                    }

                }else{
                    return ['code'=>1002,'message'=>'很抱歉,没有找到绑卡信息!'];
                }
            }else{
                return ['code'=>1004,'message'=>'很抱歉,没有找到用户信息!'];
            }
        }
    }

}
